<script>
import {apiCategoryList, apiFileRemove, apiProductAdd} from "@/api/api";

function processRawUrl(url) {
  if (url && !/^https?:\/\//.test(url)) {
    url = url.startsWith('/api') ? url : ("/api" + url);
    //   为了经过前端代理
  }
  return url;
}

function toRawUrl(url){
  const number = url.split("/").length - 1;
  return url.split("/")[number];
}


export default {
  name: "ProductPublish",
  data(){
    return {
      uploadUrl: "/api/file/upload/", // 图片上传Url
      sizeMax : 10,
      uploadHeaders : {
        token: localStorage.getItem("token")
      },
      categories:[
        {id: 1, name: "家居用品"},
        {id: 2, name: "数码产品"},
      ],
      form: {
        name: "",
        description: "",
        price: null,
        imageUrl: "",
        categoryId: "",
        productImages: []
      },
      rules: {
        name: [
          { required: true, message: '请输入商品名称', trigger: 'blur' },
        ],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (value < 0) {
                callback(new Error('价格不能小于0'));
              } else if (value > 5000) {
                callback(new Error('价格不能超过5000'));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        imageUrl: [
          { required: true, message: '请上传图片', trigger: 'change' },
        ],
        categoryId: [
          { required: true, message: '请选择分类', trigger: 'change' },
        ],
      },
      // 文件名和Url的字典
      fileList: {},
      fileListForVue:[]
    }

  },
  created() {
    this.loadCategoryList();
  },
  beforeDestroy() {
    if(this.fileList){
      for (const key in this.fileList){
        this.handleRemove(key);
      }
    }
  },
  methods:{
    // 上传成功
    uploadSuccess(res, uploadFile){
      if (res.code !== 200){
        this.$message.error(`图片上传失败 ${res.message}`);
      }
      let url = res.data;
      url = processRawUrl(url);
      if(!this.form.imageUrl){ // 首页展示图
        this.form.imageUrl = url;
        const elementNode = document.querySelector('.el-upload-list__item');
        elementNode.querySelector("a").innerText = "首页展示 " + elementNode.innerText.toString()
      }
      this.fileList[uploadFile.name] = url;
      this.$message.success("图片上传成功");
    },
    // 上传前
    beforeUpload(file){
      if (this.fileList[file.name]){
        this.$message.info("文件名重复！");
        return false;
      }
      const isImg = file.type.startsWith("image/");
      const isLt5M = file.size / 1024 / 1024 < this.sizeMax; // 大小限制 5 MB
      if (!isImg){
        this.$message.error("必须是图片类型");
        return false;
      }
      if (!isLt5M){
        this.$message.error(`图片大小限制 ${this.sizeMax} MB`);
        return false;
      }
      return true;
    },
    // 获取分类数据
    loadCategoryList(){
      apiCategoryList().then(res => {
        if (res.code === 200){
          this.categories = res.data;
        }else{
          this.$message.error(`商品类型列表请求失败 ${res.message}`);
        }
      });
    },
    onPublish(){
      this.$refs.Form.validate(valid =>{
        if(!valid){
          this.$message.error("请正确填写表单！");

        }else{
          for (const key in this.fileList) {
            this.form.productImages.push({productId: "", productImageUrl: this.fileList[key]});
          }
          apiProductAdd(this.form).then(res => {
            if(res.code === 200){
              this.$message.success("发布成功");
              this.fileList = null;
              this.$router.push("/product");
            }else{
              this.$message.error(`发布失败 ${res.message}`);
            }
          })
        }
      })
    },
    handleRemove(file) {
      console.log(file ,this.fileList)
      apiFileRemove(toRawUrl(this.fileList[file.name])).then(res => {
        if (res.code===200){
          this.$message.success("服务端文件已删除");
        }else {
          this.$message.error(`服务端文件删除失败 ${res.message}`);
        }
      })
    },
    onPreview(file){
      // 清除之前的高亮
      const elementNodeListOf = document.querySelectorAll('.el-upload-list__item');
      elementNodeListOf.forEach(item => {
        const length = item.innerText.split(" ").length;
        if (length > 1){
          item.querySelector("a").innerText = item.innerText.split(" ")[1];
        }
      });

      // 找到当前预览的 DOM 元素并高亮
      const previewItem = Array.from(elementNodeListOf).find(item =>{
          return item.innerText.trim() === file.name
      }
      );
      if (previewItem) {
        this.form.imageUrl = this.fileList[previewItem.innerText.toString()];
        previewItem.querySelector("a").innerText = "首页展示 " + previewItem.innerText.toString()
      }
    }
  }
}
</script>

<template>
  <div class="product-bg">
  <div class="content-wrap">
    <el-row type="flex" justify="center" align="middle" style="height: 100%;width:100%">
      <el-card class="product-card" style="min-width: 480px;min-height: 300px;margin-bottom: 0" shadow="always">
        <div class="product-title">商品发布</div>
        <el-form
            ref="Form"
            style="max-width: 600px"
            :model="form"
            :rules="rules"
            label-width="auto"
        >
          <!--     商品名称       -->
          <el-form-item label="商品名称" prop="name">
            <el-input
                prefix-icon="el-icon-goods"
                v-model="form.name"
                style="width: 100%"
                placeholder="请输入商品名称"
            />
          </el-form-item>
          <!--     商品描述       -->
          <el-form-item label="商品描述" prop="description">
            <el-input class="resizable-textarea" type="textarea" v-model="form.description"></el-input>
          </el-form-item >
          <!--     商品价格       -->
          <el-form-item label="商品价格" prop="price">
            <el-input-number :precision="2" v-model="form.price" :min="0.01" :max="5000.00" controls-position="right">
            </el-input-number>
          </el-form-item>
          <!--     商品分类       -->
          <el-form-item label="商品分类" prop="categoryID">
            <el-select v-model="form.categoryId" placeholder="商品分类" clearable filterable>
              <el-option v-for="(item) in categories" v-bind:key="item.id" v-bind:label="item.name" v-bind:value="item.id"></el-option>
            </el-select>
          </el-form-item>
          <!--     商品图片       -->
          <el-form-item label="商品图片" prop="imageUrl">
            <el-upload
                class="img-uploader"
                :action="uploadUrl"
                :show-file-list="true"
                :on-success="uploadSuccess"
                :before-upload="beforeUpload"
                :on-remove="handleRemove"
                :on-preview="onPreview"
                :headers="uploadHeaders"
                :file-list="fileListForVue"
                :limit="9"
                list-type="picture"
                accept="image/*">
<!--              <img v-if="form.imageUrl" :src="form.imageUrl" class="upload-img" alt="上传的图片">-->
              <i class="el-icon-plus img-uploader-icon"> 文件大小限制 {{ sizeMax }} MB</i>
            </el-upload>
          </el-form-item>
          <!--     发布按钮       -->
          <div style="display: flex;align-items: center;justify-content: center">
            <el-form-item class="no-margin" label-width="0" style="margin-bottom: 0">
              <el-button type="primary" @click="onPublish">发布</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-card>
    </el-row>
  </div>
  </div>
</template>

<style scoped lang="less">
/* 高亮当前选中的图片 */
.product-bg {
  height: 100%;
  background: url("@/assets/bg/bg.png") center;
  background-size: cover;
  width: 100%;
  //padding: 32px 1rem 1rem;
  margin: 0 0 0;
  overflow: auto;
}

.product-card {
  max-width: 1200px;
  margin: 0 auto;
  border-radius: 16px;
  box-shadow: 0 4px 24px rgba(64,158,255,0.08);
  padding: 24px;
}
.product-title {
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 24px;
}
.upload-img {
  width: 80px;
  height: 80px;
  border-radius: 8px;
  object-fit: cover;
  border: 1px solid #eee;
}
.content-wrap{
  width: 100%;
  min-height: calc(100vh - 60px);
  display: flex;
  justify-content: center;
  align-items: center;
}
.img-uploader-icon{
  color: gray; border: 2px dashed #bbbbbb;padding: 1rem;border-radius: 4px;
}
.product-card{
  border-radius: 16px;
  padding: 32px 24px 0;
  box-shadow: 2px 4px 10px rgba(64, 158, 255, 0.5) !important
}
.product-title{
  text-align: center;
  font-size: 2rem;
  font-weight: bold;
  color: #409EFF;
  margin-bottom: 24px;
  text-shadow: 1px 2px 5px rgba(0, 0, 139, 0.4);
}

.resizable-textarea :deep(.el-textarea__inner) {
  resize: both;       /* 允许调整宽高 */
  min-width: 200px;   /* 最小宽度 */
  min-height: 100px;  /* 最小高度 */
  max-width: 400px;   /* 最大宽度 */
  max-height: 300px;  /* 最大高度 */
  //overflow: auto;     /* 内容超出时显示滚动条 */
}

</style>